<?php

require_once 'lib.php';
require_once 'table.csv.php';



/**
 * class CSVGuestbook
 * 
 * CSV implementation
 * 
 * @author Kirill Krasnoschekov
 */
class CSVGuestbook extends Guestbook 
{
    // Tables
    private $msgTable;
    private $commentTable;
    


    /**
     * Constructor
     * 
     * @author Kirill Krasnoschekov
     */
    public function __construct()
    {
        
        // Schema for the messages table
        // (primary key is included automatically)
        $msgSchema = array(
                'name' => array('length' => 24),
                'text' => array('length' => 1024), 
                'timestamp' => array('timestamp' => True)
                );
            
        // Schema for the comments table
        // (primary key is included automatically)
        $commentSchema = array(
                'msgid' => array('index' => True),
                'name' => array('length' => 24),
                'text' => array('length' => 1024), 
                'timestamp' => array('timestamp' => True)
                );
            
        $this->msgTable = new CSVTable($msgSchema, 'messages');
        $this->commentTable = new CSVTable($commentSchema, 'comments');
    }
    
    /**
     * Destructor
     */
    public function __destruct() {}



    /**
     * CountPages
     * 
     * @return int Number of pages
     * @author Kirill Krasnoschekov
     */
    public function CountPages()
    {
        return ceil($this->msgTable->CountRows() / $this->messagesPerPage);
    }



    /**
     * FetchMessages
     * 
     * @param int $page Page for which to fetch messages
     * @return array List of messages
     * @author Kirill Krasnoschekov
     */
    public function FetchMessages($page)
    {
        // Calculating message numbers on the given page
        $numStart = $page * $this->messagesPerPage;
        $numEnd = $numStart + $this->messagesPerPage;

        return $this->TimestampToDates(
                $this->msgTable->Select(array(), $numStart, $numEnd, True));
    }
    
    /**
     * FetchComments
     * 
     * @return array List of comments
     * @author Kirill Krasnoschekov
     */
    public function FetchComments($msgid)
    {
        return $this->TimestampToDates(
                $this->commentTable->Select(array('msgid' => $msgid)));
    }


    
    /**
     * AddMessage
     *
     * @param string $name User name
     * @param string $text Message text 
     * @return True if succeed, False otherwise
     * @author Kirill Krasnoschekov
     */
    public function AddMessage($name, $text)
    {
        // Inserting the message
        return $this->msgTable->Insert(array('name' => $name, 
                                             'text' => $text));
    }
    
    /**
     * AddComment
     *
     * @param int $msgid Id of the message comment is for 
     * @param string $name User name
     * @param string $text Message text 
     * @return True if succeed, False otherwise
     * @author Kirill Krasnoschekov
     */
    public function AddComment($msgid, $name, $text)
    {
        // Checking if message does not exist
        if ( !$this->MessageExists($msgid) )
        {
            die(self::$err['MSGID_NOT_FOUND']);
        }
        
        // Inserting the comment
        return $this->commentTable->Insert(array('msgid' => $msgid, 
                                                 'name' => $name, 
                                                 'text' => $text));
    }

    /**
     * Delete the message
     *  
     * @param int $msgid Id of the message
     * @return True if succeed, False otherwise
     * @author Kirill Krasnoschekov
     */
    public function DeleteMessage($msgid)
    {
        // Getting ids of the comments to this message
        $comments = $this->FetchComments($msgid);
        
        // Deleting comments
        foreach ( $comments as $i => $comment )
        {
            $this->commentTable->Delete($comment['id']);
        }
        
        // Deleting the message
        return $this->msgTable->Delete($msgid);
    }
    
    
    /**
     * Delete the comment
     *  
     * @param int $msgid Id of the comment
     * @return True if succeed, False otherwise
     * @author Kirill Krasnoschekov
     */
    public function DeleteComment($commentid)
    {
        return $this->commentTable->Delete($commentid);
    }
    
    /**
     * Update the message
     * 
     * @param int $msgid Id of the comment
     * @param string $name User name
     * @param string $text Message text 
     * @return True if succeed, False otherwise
     * @author Kirill Krasnoschekov
     */
    public function UpdateMessage($msgid, $name, $text)
    {
        // Checking if message does not exist
        if ( !$this->MessageExists($msgid) )
        {
            die(self::$err['MSGID_NOT_FOUND']);
        }

        return $this->msgTable->Update($msgid, array('name' => $name, 
                                                     'text' => $text));
    }
    
    /**
     * Check if message with given id exists
     * 
     * @param int $msgid Id of the message
     * @author Kirill Krasnoschekov
     */
    protected function MessageExists($msgid)
    {
        return $this->msgTable->Exists($msgid);
    }
    
    /**
     * Check if comment with given id exists
     * 
     * @param int $msgid Id of the comment
     * @author Kirill Krasnoschekov
     */
    protected function CommentExists($commentid)
    {
        return $this->commentTable->Exists($commentid);
    }
    
    /**
     * Converts timestamp to human-readable date in each record
     * 
     * @param array $records
     * @return array The same array as received
     * @author Kirill Krasnoschekov
     */
    private function TimestampToDates($records)
    {
        for ( $i = 0; $i < count($records); $i++ )
        {
            $records[$i]['timestamp'] = date("Y-m-d H:i:s", $records[$i]['timestamp']); 
        }
        
        return $records;
    }        
}

?>